package com.ruoyi.fun.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.fun.domain.EcUserAddress;
import com.ruoyi.fun.service.IEcUserAddressService;

/**
 * 移动端收货地址Controller
 * 
 * @author ruoyi
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/mobile/address")
public class EcMobileAddressController extends BaseController
{
    @Autowired
    private IEcUserAddressService ecUserAddressService;

    /**
     * 查询当前用户的收货地址列表
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(value = "userId", required = false) Long userId)
    {
        try {
            // 从安全上下文获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();
            
            // 如果传入了userId参数，验证是否与当前用户一致（安全检查）
            if (userId != null && !currentUserId.equals(userId)) {
                return error("无权限访问其他用户的地址信息");
            }
            
            EcUserAddress ecUserAddress = new EcUserAddress();
            ecUserAddress.setUserId(currentUserId);
            List<EcUserAddress> list = ecUserAddressService.selectEcUserAddressList(ecUserAddress);
            return success(list);
        } catch (Exception e) {
            logger.error("获取用户地址列表失败：" + e.getMessage(), e);
            return error("获取地址列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取收货地址详细信息
     */
    @GetMapping(value = "/{addressId}")
    public AjaxResult getInfo(@PathVariable("addressId") Long addressId)
    {
        try {
            // 从安全上下文获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();
            // 获取当前用户的组织ID
            Long currentOrgId = getOrgId();
            
            // 使用基于userId和addressId的方法获取地址信息
            EcUserAddress address = ecUserAddressService.selectEcUserAddressByAddressIdAndUserId(addressId, currentUserId);
            if (address == null) {
                return error("地址不存在或无权限访问");
            }
            
            return success(address);
        } catch (Exception e) {
            logger.error("获取地址详情失败：" + e.getMessage(), e);
            return error("获取地址详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增收货地址
     */
    @Log(title = "收货地址", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcUserAddress ecUserAddress)
    {
        try {
            // 从安全上下文获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();
            
            // 设置用户ID为当前登录用户（安全检查）
            ecUserAddress.setUserId(currentUserId);
            
            // 如果设置为默认地址，先将该用户的其他地址设为非默认
            if ("1".equals(ecUserAddress.getIsDefault())) {
                ecUserAddressService.updateUserDefaultAddress(currentUserId, null);
            }
            
            return toAjax(ecUserAddressService.insertEcUserAddress(ecUserAddress));
        } catch (Exception e) {
            logger.error("新增地址失败：" + e.getMessage(), e);
            return error("新增地址失败：" + e.getMessage());
        }
    }

    /**
     * 修改收货地址
     */
    @Log(title = "收货地址", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcUserAddress ecUserAddress)
    {
        try {
            // 从安全上下文获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();
            // 获取当前用户的组织ID
            Long currentOrgId = getOrgId();
            
            // 使用基于userId和addressId的方法获取原地址信息进行权限验证
            EcUserAddress existingAddress = ecUserAddressService.selectEcUserAddressByAddressIdAndUserId(ecUserAddress.getAddressId(), currentUserId);
            if (existingAddress == null) {
                return error("地址不存在或无权限修改");
            }
            
            // 设置用户ID为当前登录用户（安全检查）
            ecUserAddress.setUserId(currentUserId);
            
            // 如果设置为默认地址，先将该用户的其他地址设为非默认
            if ("1".equals(ecUserAddress.getIsDefault())) {
                ecUserAddressService.updateUserDefaultAddress(currentUserId, ecUserAddress.getAddressId());
            }
            
            return toAjax(ecUserAddressService.updateEcUserAddress(ecUserAddress));
        } catch (Exception e) {
            logger.error("修改地址失败：" + e.getMessage(), e);
            return error("修改地址失败：" + e.getMessage());
        }
    }

    /**
     * 删除收货地址
     */
    @Log(title = "收货地址", businessType = BusinessType.DELETE)
    @DeleteMapping("/{addressId}")
    public AjaxResult remove(@PathVariable Long addressId)
    {
        try {
            // 从安全上下文获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();
            // 获取当前用户的组织ID
            Long currentOrgId = getOrgId();
            
            // 使用基于userId和addressId的方法验证地址是否属于当前用户
            EcUserAddress address = ecUserAddressService.selectEcUserAddressByAddressIdAndUserId(addressId, currentUserId);
            if (address == null) {
                return error("地址不存在或无权限删除");
            }
            
            return toAjax(ecUserAddressService.deleteEcUserAddressByAddressIds(new Long[]{addressId}));
        } catch (Exception e) {
            logger.error("删除地址失败：" + e.getMessage(), e);
            return error("删除地址失败：" + e.getMessage());
        }
    }

    /**
     * 设置默认地址
     */
    @Log(title = "设置默认地址", businessType = BusinessType.UPDATE)
    @PutMapping("/setDefault/{addressId}")
    public AjaxResult setDefault(@PathVariable Long addressId)
    {
        try {
            // 从安全上下文获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();
            // 获取当前用户的组织ID
            Long currentOrgId = getOrgId();
            
            // 使用基于userId和addressId的方法获取地址信息
            EcUserAddress address = ecUserAddressService.selectEcUserAddressByAddressIdAndUserId(addressId, currentUserId);
            if (address == null) {
                return error("地址不存在或无权限设置为默认地址");
            }
            
            // 先将该用户的其他地址设为非默认
            ecUserAddressService.updateUserDefaultAddress(currentUserId, addressId);
            
            // 设置当前地址为默认
            address.setIsDefault("1");
            return toAjax(ecUserAddressService.updateEcUserAddress(address));
        } catch (Exception e) {
            logger.error("设置默认地址失败：" + e.getMessage(), e);
            return error("设置默认地址失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户默认地址
     */
    @GetMapping("/default")
    public AjaxResult getDefaultAddress(@RequestParam(value = "userId", required = false) Long userId)
    {
        try {
            // 从安全上下文获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();
            
            // 如果传入了userId参数，验证是否与当前用户一致（安全检查）
            if (userId != null && !currentUserId.equals(userId)) {
                return error("无权限访问其他用户的地址信息");
            }
            
            EcUserAddress defaultAddress = ecUserAddressService.selectDefaultAddressByUserId(currentUserId);
            return success(defaultAddress);
        } catch (Exception e) {
            logger.error("获取用户默认地址失败：" + e.getMessage(), e);
            return error("获取默认地址失败：" + e.getMessage());
        }
    }



}